import { Component, ElementRef, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { HttpModule } from '@angular/http';
import { HttpClientModule, HttpClient, HttpErrorResponse } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { RouterModule, Router, ActivatedRoute } from '@angular/router';

import { Service } from '../../../server/server';
import { CudTableService } from '../../../public/serve/cud-table/cud-table.service';
import { Data } from '@angular/router/src/config';
import * as moment from 'moment';
declare var $: any;

@Component({
  selector: 'app-institution-add',
  templateUrl: './institution-add.component.html',
})
export class InstitutionAddComponent implements OnInit {

  constructor(private http: HttpClient, private router: Router, private server: Service, private cudTableService: CudTableService) { }

  ngOnInit() {
    this.createUserId = this.server.getuser();
    // this.superiorAdd = "中国少年儿童出版总社";
    // this.superiorAddId = '12aa1c87305f4271a90bffeb28315ca2';
    //首次进入接受tree数据
    this.institutiontreeidnameeventEmit = this.server.institutiontreeidnameeventEmit.subscribe((value: any) => {
      this.superiorAdd = value.institutionName;
      this.superiorAddId = value.institutionId;
    })
    this.institutiontwoeventEmit = this.server.institutiontwoeventEmit.subscribe((value: any) => {
      //console.log(this.twomodel)
      this.twomodel = value;
      this.server.institutionMolde = value;
      $("#addtitle").html("<span class='glyphicon glyphicon-plus'></span> 新增机构");
      this.defaultTime(this.superiorAddId);
      this.resetZ();

    });

    //this.maxDate = new Date();
    this.minDate = new Date();
  }

  //取消订阅
  public institutiontreeidnameeventEmit: any;
  public institutiontwoeventEmit:any;
  ngOnDestroy() {
    if (this.institutiontreeidnameeventEmit || this.institutiontwoeventEmit) {
      this.institutiontreeidnameeventEmit.unsubscribe();
      this.institutiontwoeventEmit.unsubscribe();
    }
  }

  ngDoCheck(){
    
  }

  //date
  public minDate:Date;
  public maxDate:Date;

  @Output()
  addOutput: EventEmitter<any> = new EventEmitter();
  //发射引导值
  @Output()
  addstepOutput: EventEmitter<any> = new EventEmitter();


  @Input() superiorAdd: any;

  @Input() superiorAddId: any;
  //清空
  @ViewChild('FormAdd') formElement:HTMLFormElement
  reset(){
    this.router.navigate(['user/institution']);
    $("#mechanismAdd").modal("hide");
    this.resetZ();
  }

  public resetZ(){
    this.formElement.reset();
    setTimeout(()=> { 
      this.adddate.enabled = true;
      this.adddate.institutionType= '0';
      this.adddate.jgServerType = '0';
      this.adddate.validDate = null;
     }, 100)
  }
  public createUserId: any;
  public today = new Date().toISOString().split('T')[0];
  public step: number = 0;
  public twomodel:boolean = false;

  //datatype
  adddate: Datatype = {
    createUserId: this.createUserId,
    address: '',
    city: '',
    contactName: '',
    createDate: '',
    description: '',
    enabled: true,
    industry: '',
    institutionDisplayName: '',
    institutionId: '',
    institutionName: '',
    institutionOrder: '',
    institutionType: '0',
    jgServerType:'0',
    lastUpdatedDate: '',
    lastUpdatedUserId: '',
    nature: '',
    parentId: '',
    phone: '',
    postcode: '',
    province: '',
    validDate:'',
  };
  stepadds: any;

  submitAdd(val) {
    //console.log(val)
    this.adddate.createUserId = this.createUserId;
    this.adddate.parentId = this.superiorAddId;
    this.adddate.validDate = this.server.formatDate(this.adddate.validDate)
    this.adddate.enabled = Number(this.adddate.enabled)
    let url = this.server.baseUrl + 'admin/institutions/add';
    let data: Datatype = this.adddate;
    this.cudTableService.postRequest(url, data).then((res: any) => {
      if (res.result_code == '0000') {
        this.server.institutioneventEmit.emit(res.result)
        //prompt
        this.server.prompt = { prompt: true, success: true, fail: false, promptStatement: res.message };
        this.server.promptclose;
        this.addOutput.emit(res.result_code);
        this.reset();
        //新增机构退出
        if (val == 0) {
          this.stepadds = { step: 0, treeopp: false }
          this.addstepOutput.emit(this.stepadds);

        }
        //新增机构并添加管理员
        if (val == 1 && res.result) {
          this.stepadds = { step: 3, treeopp: true, title: "为机构添加管理员", btn: "下一步" }
          this.addstepOutput.emit(this.stepadds);
          setTimeout(() => {
            $("#adminAdd").modal("show");
            this.stepadds = { step: 3, treeopp: false, title: "为机构添加管理员", btn: "下一步" }
            this.addstepOutput.emit(this.stepadds);
            this.server.institutionbtneventEmit.emit(true);
          }, 500)
        } else {
         
        }
        //update
      } else {
        this.server.prompt = { prompt: true, success: false, fail: true, promptStatement: res.message };
        this.server.promptclose;
      }
    }).catch()
  }

  //到期时间
  public defaulttime:any;
  public defaultTime(id){
    let url = this.server.baseUrl + 'admin/institutions/initOrder/'+id;
    this.cudTableService.getRequest(url ).then((res: any) => {
      //res = res.json();
      if (res.result_code == '0000') {
       this.defaulttime=res.validDate;
       //this.maxDate = moment(this.defaulttime).toDate();
       if(this.defaulttime){
          let y = this.defaulttime.substring(0,4);
          let m = this.defaulttime.substring(5,7);
          let d = this.defaulttime.substring(8,11);
         // this.maxDate = new Date(y,m-1,d);
          setTimeout(() => {
            this.adddate.validDate=new Date(y,m-1,d);
          }, 300);
          
          //console.log( this.defaulttime,this.adddate.validDate)
        }
      }else{
        this.server.prompt = { prompt: true, success: false, fail: true, promptStatement: res.message };
        this.server.promptclose;
      }
    })
  }

  
}
export class Datatype {
  address: string;
  city: string;
  contactName: string;
  createDate: string;
  createUserId: string;
  description: string;
  enabled: any;
  industry: string;
  institutionDisplayName: string;
  institutionId: string;
  institutionName: string;
  institutionOrder: string;
  institutionType: string;
  jgServerType:string;
  lastUpdatedDate: string;
  lastUpdatedUserId: string;
  nature: string;
  parentId: string;
  phone: string;
  postcode: string;
  province: string;
  validDate: any;
}

